import { defineStore } from 'pinia';

export const usePrintTaskStore = defineStore('printTask', {
    state: () => ({
        ids: [] as number[],
        queue: [] as { id: number; task: () => Promise<void> }[],
        status: 0 as 0 | 1 | 2, // 0-待打印 1-打印中 2-已暂停
        message: '' as string
    }),
    actions: {
        stopTask() {
            console.log("PrintTask，停止任务，剩余任务:", this.queue.length);
            this.status = 2;
        },
        startTask() {
            console.log("PrintTask，启动任务，剩余任务:", this.queue.length);
            this.status = 0;
            this.run();
        },
        clearTask(){
            this.ids = [];
            this.status = 0;
        },
        addTask(task: { id: number; task: () => Promise<void> }) {
            if (this.ids.includes(task.id)) {
                console.log("PrintTask，任务正在执行中，加入队列失败，id:" + task.id);
                return false;
            }
            this.ids.push(task.id);
            this.queue.push(task);
            console.log("PrintTask，任务加入队列成功，id,status:" + task.id, this.status);
            if (this.status === 0) {
                this.run();
            }
            return true;
        },
        async run() {
            this.status = 1;
            while (this.status === 1 && this.queue.length > 0) {
                let index = -1;
                try {
                    const task = this.queue.shift();
                    if (task) {
                        index = this.ids.indexOf(task.id);
                        await task.task();
                        console.log("PrintTask，任务执行完成，id:" + task.id);
                        this.message = '';
                    }
                } catch (e:any) {
                    this.message = e.message;
                    console.log("PrintTask，任务执行出现异常", e);
                } finally {
                    if (index !== -1) {
                        this.ids.splice(index, 1); // 删除元素
                    }
                    continue; // xiaoch 此行不要去掉，否则下一个任务不会继续执行
                }
            }
            this.status = 0;
        },
    },
});

export default usePrintTaskStore;